package com.taoye.thread;

import cn.hutool.core.date.DateUtil;

public class Demo31 {
	public static void main(String[] args) throws InterruptedException {
		Demo31Service service = new Demo31Service();
		Thread t = new Demo31ThreadA(service);
		t.setName("A");
		t.start();
		Thread t1 = new Demo31ThreadB();
		t1.setName("B");
		t1.start();
	}
}

class Demo31Service {

	/**
	 * 这里非静态方法，锁定的是实例化的对象
	 */
	public synchronized void fun1() {
		try {
			System.out.println(Thread.currentThread().getName() + "线程执行了fun1，当前时间：" + DateUtil.now());
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getName() + "线程fun1执行结束，当前时间：" + DateUtil.now());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 这里是静态方法，使用的是类锁
	 */
	public static synchronized void fun2() {
		try {
			System.out.println(Thread.currentThread().getName() + "线程执行了fun2，当前时间：" + DateUtil.now());
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getName() + "线程fun2执行结束，当前时间：" + DateUtil.now());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

class Demo31ThreadA extends Thread {
	Demo31Service service = new Demo31Service();

	public Demo31ThreadA(Demo31Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		// 这里调用的不是静态方法
		service.fun1();
	}
}

class Demo31ThreadB extends Thread {

	@Override
	public void run() {
		Demo31Service.fun2();
	}
}
